package cn.zf233.xcloud.intercept;

import cn.zf233.xcloud.commom.Const;
import cn.zf233.xcloud.commom.R;
import cn.zf233.xcloud.commom.enums.UserRoleENUM;
import cn.zf233.xcloud.util.JsonUtil;
import cn.zf233.xcloud.vo.UserVo;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zf233 on 2021/1/17
 * 管理员拦截
 */
public class PermissionCheckAdmin implements HandlerInterceptor {


    private static final Map<String, String> RESPONSE_JSON_OF_INTERCEPT_URI;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserVo current = (UserVo) request.getSession().getAttribute(Const.CURRENT_USER);
        boolean flag;
        String msg;
        if (current == null) {
            msg = "登陆失效，请重新登录";
            flag = false;
        } else {
            if (!UserRoleENUM.ADMIN.getCode().equals(current.getRoleNum())) {
                flag = false;
                msg = "权限不足";
            } else {
                flag = true;
                msg = "校验通过";
            }
        }
        if (flag) {
            return true;
        } else {
            String targetUri = request.getRequestURI();
            if (!RESPONSE_JSON_OF_INTERCEPT_URI.containsKey(targetUri)) {
                response.setContentType("text/json; charset=UTF-8");
                response.getWriter().println(JsonUtil.toJson(R.createByErrorIllegalArgument(msg)));
            } else {
                request.getRequestDispatcher("/user/jump/index").forward(request, response);
            }
            return false;
        }
    }

    static {
        String[] uriArray = {
                "/admin",
                "/admin/agreement",
                "/admin/app",
                "/admin/starter",
        };
        RESPONSE_JSON_OF_INTERCEPT_URI = new HashMap<>(uriArray.length);
        Arrays.stream(uriArray).forEach(uri -> RESPONSE_JSON_OF_INTERCEPT_URI.put(uri, uri));
    }
}
